package cn.qiao.benchmark;

import org.openjdk.jmh.annotations.*;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.concurrent.TimeUnit;

/**
 * desc:
 *
 * @author qiao
 * @date 2024年02月05日 21:25
 */
@BenchmarkMode(Mode.All)
@Warmup(iterations = 1)//预热轮数
@Measurement(iterations = 1, time = 1, timeUnit = TimeUnit.SECONDS)
@Threads(2)//线程数
@Fork(1) //fork的次数，如果想用Autowired自动注入，这个填0
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
public class RedisBenchmark {


    private JedisServiceImpl jedisService;

    private LettuceServiceImpl lettuceService;


    @Setup
    public void init(){
        jedisService = new JedisServiceImpl(getJedisPool());
        lettuceService = new LettuceServiceImpl(getLettuce());

    }

    private RedisConnectionFactory getLettuce() {
        RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration();
        redisConfig.setHostName("localhost");
        redisConfig.setPort(6379);
        LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisConfig);
        lettuceConnectionFactory.afterPropertiesSet();
        return lettuceConnectionFactory;
    }

    JedisPool getJedisPool(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(10); // 设置最大连接数
        jedisPoolConfig.setMaxIdle(5);   // 设置最大空闲连接数

        // 创建 Jedis 连接池
       return new JedisPool(jedisPoolConfig, "localhost", 6379,3,null,3);
    }


    @Benchmark
    public void jedis_set(){
        String key = "jedis-test";
        jedisService.set(key,"test");
    }


    @Benchmark
    public void lettuce_set(){
        String key = "jedis-test";
        lettuceService.set(key,"test");
    }

}
